package translate

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"github.com/bitly/go-simplejson"
)

const (
	BaiduTranslateAPIURL = "http://api.fanyi.baidu.com/api/trans/vip/translate"
	BaiduAppID           = "20240331002010100"
	BaiduAppKey          = "ye5lIblmYMwYPtVvKaNx"
	Salt                 = "Fusion12#$"
)

func Md5(s string) string { //计算md5的值
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

// func u2s(form string) (to string, err error) { //unicode转字符串
//
//		bs, err := hex.DecodeString(strings.Replace(form, `\u`, ``, -1))
//		if err != nil {
//			return
//		}
//		for i, bl, br, r := 0, len(bs), bytes.NewReader(bs), uint16(0); i < bl; i += 2 {
//			binary.Read(br, binary.BigEndian, &r)
//			to += string(r)
//		}
//		return
//	}
func translate(word string) []byte { //调用api进行翻译
	data := make(url.Values)
	data["q"] = []string{word}
	data["from"] = []string{"auto"}
	data["to"] = []string{"auto"}
	data["appid"] = []string{BaiduAppID}
	data["salt"] = []string{Salt}
	sign := Md5(BaiduAppID + word + Salt + BaiduAppKey) //签名密钥
	data["sign"] = []string{sign}

	res, err := http.PostForm(BaiduTranslateAPIURL, data)
	if err != nil {
		fmt.Println(err.Error())
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err.Error())
	}
	return body
}
func Trans(words string) string { //翻译函数
	body := translate(words)
	js, err := simplejson.NewJson(body)
	if err != nil {
		panic(err.Error())
	}
	dst := js.Get("trans_result").GetIndex(0).Get("dst").MustString()
	return dst
}
